package com.pureut.storage.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.api.FeignProductionService;
import com.pureut.storage.domain.MiscellaneousReceipt;
import com.pureut.storage.domain.MiscellaneousReceiptDetail;
import com.pureut.storage.domain.PublicGoods;
import com.pureut.storage.domain.WmsStockInfo;
import com.pureut.storage.domain.system.domain.SysDocument;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.MiscellaneousPurchaseReceiptExport;
import com.pureut.storage.mapper.MiscellaneousReceiptDetailMapper;
import com.pureut.storage.mapper.MiscellaneousReceiptMapper;
import com.pureut.storage.mapper.PublicGoodsMapper;
import com.pureut.storage.mapper.WmsStockInfoMapper;
import com.pureut.storage.service.MiscellaneousReceiptDetailService;
import com.pureut.storage.service.MiscellaneousReceiptService;
import com.pureut.storage.service.WarehouseService;
import com.pureut.storage.service.WmsStockInfoService;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.vo.MiscellaneousReceiptVo;
import com.pureut.storage.vo.MiscellaneousVo;
import com.pureut.storage.vo.PickingRestDbVo;
import com.pureut.storage.vo.UpdateStatusByQualityVo;
import com.pureut.system.api.*;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.domain.SysUser;
import com.pureut.system.api.vo.MaterialNumberAndBatchNoVo;
import com.pureut.system.api.vo.QualityInspectionDocumentVo;
import com.pureut.system.api.vo.QualitySchemeConfigurationVo;
import com.pureut.system.api.vo.UpdateQualityStatusVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/***
 *
 * Author:C
 * Date:2022/12/28 15:45
 * @DESC
 */
@Service
public class MiscellaneousReceiptServiceImpl extends ServiceImpl<MiscellaneousReceiptMapper, MiscellaneousReceipt> implements MiscellaneousReceiptService {

    @Resource
    MiscellaneousReceiptMapper miscellaneousReceiptMapper;

    @Resource
    OrderFeignService orderFeignService;

    @Resource
    WarehouseService warehouseService;

    @Resource
    FeignService feignService;

    @Resource
    MiscellaneousReceiptDetailMapper miscellaneousReceiptDetailMapper;

    @Resource
    WmsStockInfoMapper wmsStockInfoMapper;


    @Resource
    WmsStockInfoService wmsStockInfoService;

    @Resource
    PublicGoodsMapper publicGoodsMapper;

    @Resource
    MiscellaneousReceiptDetailService miscellaneousReceiptDetailService;

    @Resource
    SystemDocumentFeignService systemDocumentFeignService;

    @Resource
    FeignProductionService feignProductionService;

    //用户信息
    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    QualityFeginService qualityFeginService;

    /**
     * 其他入库列表
     *
     * @param miscellaneousReceiptVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<MiscellaneousReceiptDto> getMiscellaneousList(MiscellaneousReceiptVo miscellaneousReceiptVo) {
        List<MiscellaneousReceiptDto> miscellaneousList = miscellaneousReceiptMapper.getMiscellaneousList(miscellaneousReceiptVo);
        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取其他入库状态字典值
        List<SysDictData> statusArray = DictUtils.getDictCache("miscellaneous_receipt_status");
        Map<String, String> miscellaneousStatusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取其他入库收发类型字典值
        List<SysDictData> rdArray = DictUtils.getDictCache("miscellaneous_receipt_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (MiscellaneousReceiptDto entity : miscellaneousList) {
            //其他入库状态
            entity.setStatusDict(miscellaneousStatusMap.get(String.valueOf(entity.getStatus())));
            //单据类型
            entity.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(entity.getDocumentType())));
            //收发类型
            entity.setReceiveTypeDict(rdMap.get(entity.getReceiveType()));
            //生成方式
            entity.setGenerationMethodDict(GenerationMethodEnum.getValue(entity.getGenerationMethod()));
            //单位
            entity.setUnitDict(unitMap.get(entity.getMaterialUnit()));
        }
        return miscellaneousList;
    }

    /**
     * 新增其他入库
     *
     * @param miscellaneousReceiptVo
     * @return
     */
    @Override
    public boolean addMiscellaneousReceipt(MiscellaneousReceiptVo miscellaneousReceiptVo) throws Exception {
        List<MiscellaneousVo> miscellaneousList = miscellaneousReceiptVo.getMiscellaneousList();
        List<MiscellaneousReceipt> miscellaneousReceiptList = new ArrayList<>();
        if (miscellaneousList.size() > 0) {
            for (MiscellaneousVo entity : miscellaneousList) {
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>()
                        .lambda()
                        .eq(PublicGoods::getMaterialCode, entity.getMaterialCode()));

                MiscellaneousReceipt miscellaneousReceipt = new MiscellaneousReceipt();
                String authorityCoding = feignService.getAuthorityCoding("warehouse:warehousing:other:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                miscellaneousReceipt.setReceiptNo(authorityCoding)
                        .setDeptId(SecurityUtils.getDeptId())
                        .setStatus(1)
                        .setRelationOrderNo(entity.getRelationOrderNo())
                        .setMaterialId(entity.getMaterialId())
                        .setMaterialCode(entity.getMaterialCode())
                        .setMaterialCategory(Integer.parseInt(String.valueOf(publicGoods.getMaterialType())))
                        .setPlannedWeight(entity.getPlannedWeight())
                        .setWarehousingWarehouse(entity.getWarehousingWarehouse())
                        .setWarehousTime(miscellaneousReceiptVo.getWarehousTime())
                        .setRemark(miscellaneousReceiptVo.getRemark())
                        .setDrawerBy(SecurityUtils.getUsername())
                        .setDrawerTime(new Date())
                        .setReceiveType(miscellaneousReceiptVo.getReceiveType())
                        .setDocumentType(DocumentTypeEnum.MISCELLANEOUS_RECEIPT.getCode())
                        .setGenerationMethod(GenerationMethodEnum.MANUALLY_GENERATED.getCode());
                miscellaneousReceiptList.add(miscellaneousReceipt);
            }
            return saveBatch(miscellaneousReceiptList);
        } else {
            throw new GlobalException("请至少选择一条数据");
        }
    }

    /**
     * 关结
     *
     * @param miscellaneousReceiptVo
     * @return
     */
    @Override
    public boolean close(MiscellaneousReceiptVo miscellaneousReceiptVo) {
        MiscellaneousReceipt miscellaneousReceipt = getById(miscellaneousReceiptVo.getId());
        //已完成、已关结不可重复关结；
        if (miscellaneousReceipt.getStatus() != 5 && miscellaneousReceipt.getStatus() != 6) {
            //待检验状态的单据关结后，单据状态更新为“已关结”，跳过后续操作，入库的物料显示为在库，关联的品质检验单状态更新为“已撤销”；
            if (miscellaneousReceipt.getStatus() == 3) {
                List<MiscellaneousReceiptDetail> miscellaneousReceiptDetails = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, miscellaneousReceipt.getId()));
                //获取该单据下明细数据物料号码
                List<String> materialNumberList = miscellaneousReceiptDetails.stream()
                        .filter(entity -> entity.getStatus() == 2 && entity.getStatus() == 1)
                        .map(MiscellaneousReceiptDetail::getMaterialNumber)
                        .collect(Collectors.toList());
                List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));

                if(!wmsStockInfos.isEmpty()) {

                    for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfos);
                }
                //修改对应品质检验单状态为已撤销
                UpdateQualityStatusVo updateQualityStatusVo = new UpdateQualityStatusVo();
                updateQualityStatusVo.setAssociatedNo(miscellaneousReceipt.getReceiptNo());
                updateQualityStatusVo.setStatus(8);
                qualityFeginService.updateQualityInspectionDocument(updateQualityStatusVo);
            }

            //待交接状态的单据关结后，单据状态更新为“已关结”，跳过后续操作，入库的物料显示在库
            if (miscellaneousReceipt.getStatus() == 4) {
                List<MiscellaneousReceiptDetail> miscellaneousReceiptDetails = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, miscellaneousReceipt.getId()));
                //获取该单据下明细数据物料号码
                List<String> materialNumberList = miscellaneousReceiptDetails.stream()
                        .filter(entity -> entity.getStatus() == 2 && entity.getStatus() == 1)
                        .map(MiscellaneousReceiptDetail::getMaterialNumber)
                        .collect(Collectors.toList());
                if(!materialNumberList.isEmpty()) {
                    List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                    for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfos);
                }
            }
            //待入库、部分入库状态的单据关结后，单据状态更新为“已关结”，无影响；
            //入库中的单据关结后，单据状态更新为“已关结”，已扫描过的条码为在库
            if (miscellaneousReceipt.getStatus() == 2) {
                List<MiscellaneousReceiptDetail> miscellaneousReceiptDetails = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, miscellaneousReceipt.getId()));
                //获取该单据下明细数据物料号码
                List<String> materialNumberList = miscellaneousReceiptDetails.stream()
                        .filter(entity -> entity.getStatus() == 2 && entity.getStatus() == 1)
                        .map(MiscellaneousReceiptDetail::getMaterialNumber)
                        .collect(Collectors.toList());
                if(!materialNumberList.isEmpty()) {
                    List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                    for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfos);
                }
            }
            miscellaneousReceipt.setStatus(6)
                    .setCloseReason(miscellaneousReceiptVo.getCloseReason())
                    .setClosingBy(SecurityUtils.getUsername())
                    .setClosingTime(new Date());
            return updateById(miscellaneousReceipt);
        } else {
            throw new GlobalException("已完成、已关结不可重复关结");
        }
    }

    /**
     * 删除
     *
     * @param idStr
     * @return
     */
    @Override
    public boolean deleteMiscellaneousReceipt(String idStr) {
        List<String> idList = Arrays.asList(idStr.split(","));
        if (idList.size() == 0) {
            throw new GlobalException("请至少选择一条数据");
        }
        List<MiscellaneousReceipt> miscellaneousReceiptList = new ArrayList<>();
        List<MiscellaneousReceipt> miscellaneousReceipts = miscellaneousReceiptMapper.selectList(new QueryWrapper<MiscellaneousReceipt>().lambda().in(MiscellaneousReceipt::getId, idList));
        for (MiscellaneousReceipt entity : miscellaneousReceipts) {
            if (entity.getStatus() == 1) {
                miscellaneousReceiptList.add(entity);
            } else {
                throw new GlobalException("只能删除待入库的单据");
            }
        }
        List<MiscellaneousReceipt> deleteList = new ArrayList<>();
        for (MiscellaneousReceipt entity : miscellaneousReceiptList) {
            if (entity.getGenerationMethod() == 2) {
                deleteList.add(entity);
            } else {
                throw new GlobalException("自动生成的单据不能删除");
            }
        }
        return removeByIds(deleteList);
    }

    /**
     * 修改
     *
     * @param miscellaneousReceiptVo
     * @return
     */
    @Override
    public boolean updateMiscellaneousReceipt(MiscellaneousReceiptVo miscellaneousReceiptVo) {
        MiscellaneousReceipt miscellaneousReceipt = getById(miscellaneousReceiptVo.getId());
        if (miscellaneousReceipt.getStatus() == 1) {
            miscellaneousReceipt.setReceiveType(miscellaneousReceiptVo.getReceiveType());
            miscellaneousReceipt.setWarehousTime(miscellaneousReceiptVo.getWarehousTime());
            miscellaneousReceipt.setRemark(miscellaneousReceiptVo.getRemark());
            List<MiscellaneousVo> miscellaneousList = miscellaneousReceiptVo.getMiscellaneousList();
            for (MiscellaneousVo entity : miscellaneousList) {
                miscellaneousReceipt.setRelationOrderNo(entity.getRelationOrderNo())
                        .setPlannedWeight(entity.getPlannedWeight())
                        .setWarehousingWarehouse(entity.getWarehousingWarehouse())
                        .setMaterialCode(entity.getMaterialCode())
                        .setMaterialId(entity.getMaterialId());
            }
            return updateById(miscellaneousReceipt);
        } else {
            throw new GlobalException("只能修改待入库的数据");
        }
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public MiscellaneousReceiptDto getView(Long id) {

        MiscellaneousReceiptDto miscellaneousById = miscellaneousReceiptMapper.getMiscellaneousById(id);

        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //单据类型
        miscellaneousById.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(miscellaneousById.getDocumentType())));
        //收发类型
        List<SysDictData> typeArray = DictUtils.getDictCache("miscellaneous_receipt_rd_type");
        Map<String, String> purchaseReceiptMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        miscellaneousById.setReceiveTypeDict(purchaseReceiptMap.get(miscellaneousById.getReceiveType()));
        miscellaneousById.setReceiveType(String.valueOf(miscellaneousById.getReceiveType()));

        List<MiscellaneousVo> miscellaneousVos = new ArrayList<>();
        MiscellaneousVo miscellaneousVo = new MiscellaneousVo();
        miscellaneousVo.setRelationOrderNo(miscellaneousById.getRelationOrderNo());
        miscellaneousVo.setPlannedWeight(miscellaneousById.getPlannedWeight());
        miscellaneousVo.setUnitDict(unitMap.get(miscellaneousById.getMaterialUnit()));
        miscellaneousVo.setMaterialUnit(miscellaneousById.getMaterialUnit());
        //获取仓库名称
        miscellaneousVo.setWarehousingWarehouse(Long.parseLong(miscellaneousById.getWarehousingWarehouse()));
        miscellaneousVo.setWarehousingWarehouseDict(miscellaneousById.getWarehouseName());
        //物料信息
        miscellaneousVo.setMaterialName(miscellaneousById.getMaterialName());
        miscellaneousVo.setMaterialCode(miscellaneousById.getMaterialCode());
        miscellaneousVo.setMaterialSpec(miscellaneousById.getMaterialSpec());

        miscellaneousVos.add(miscellaneousVo);
        miscellaneousById.setMiscellaneousList(miscellaneousVos);
        return miscellaneousById;
    }

    /**
     * 导出
     *
     * @param miscellaneousReceiptVo
     * @return
     */
    @Override
    public List<MiscellaneousPurchaseReceiptExport> getInfoExport(MiscellaneousReceiptVo miscellaneousReceiptVo) {
        List<MiscellaneousPurchaseReceiptExportDto> miscellaneousList;
        if (miscellaneousReceiptVo.getIdStr() == null) {
            //根据条件获取数据
            miscellaneousList = miscellaneousReceiptMapper.getMiscellaneousListOut(miscellaneousReceiptVo);

        } else {
            //根据id获取对应数据
            List<String> idList = Arrays.asList(miscellaneousReceiptVo.getIdStr().split(","));
            miscellaneousList = miscellaneousReceiptMapper.getDataByIdStr(idList);

        }
        List<MiscellaneousPurchaseReceiptExport> miscellaneousPurchaseReceiptExportList = new ArrayList<>();

        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取铺网类型标准缓存字典数据
        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取其他入库收发类型字典值
        List<SysDictData> rdArray = DictUtils.getDictCache("miscellaneous_receipt_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (MiscellaneousPurchaseReceiptExportDto entity : miscellaneousList) {
            MiscellaneousPurchaseReceiptExport miscellaneousPurchaseReceiptExport = new MiscellaneousPurchaseReceiptExport();

            BeanUtils.copyProperties(entity, miscellaneousPurchaseReceiptExport);

            //收发类型
            if (!"0".equals(miscellaneousPurchaseReceiptExport.getReceiveType())) {
                miscellaneousPurchaseReceiptExport.setReceiveType(rdMap.get(miscellaneousPurchaseReceiptExport.getReceiveType()));
            } else {
                miscellaneousPurchaseReceiptExport.setReceiveType("");
            }
            miscellaneousPurchaseReceiptExport.setMaterialNetDict(netMap.get(entity.getMaterialNetDict()));
            miscellaneousPurchaseReceiptExport.setMaterialNetTypeDict(netTypeMap.get(entity.getMaterialNetTypeDict()));
            miscellaneousPurchaseReceiptExportList.add(miscellaneousPurchaseReceiptExport);
        }
        return miscellaneousPurchaseReceiptExportList;
    }

    /**
     * 其他入库(pda)
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto miscellaneousPda(PickingRestDbVo pickingRestDbVo) throws Exception {
        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();
        MiscellaneousReceipt miscellaneousReceipt = getById(pickingRestDbVo.getId());
        if (miscellaneousReceipt.getStatus() == 1 || miscellaneousReceipt.getStatus() == 2) {
            //扫码入库
            if ("1".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("没有该仓库信息，请核实!");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setMessage("操作成功");
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据物料号码保存明细信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    MiscellaneousReceiptVo miscellaneousReceiptVo = new MiscellaneousReceiptVo();

                    MiscellaneousReceipt byId = getById(pickingRestDbVo.getId());
                    //获取其他入库列表
                    List<MiscellaneousReceiptDto> miscellaneousList = miscellaneousReceiptMapper.getMiscellaneousList(miscellaneousReceiptVo);

                    String materialNumber = pickingRestDbVo.getInputValue();
                    //查询废料管理信息
                    AjaxResult wasteData = feignProductionService.getWasteData(materialNumber);
                    WasteTubeDto data = JSON.parseObject(JSON.toJSONString(wasteData.get("data")), WasteTubeDto.class);
                    if (data.getWasteScrapNumber() == null) {
                        pickingRestDbDto.setCode("500");
                        pickingRestDbDto.setMessage("未查询到相关物料，请核实后输入!");
                        return pickingRestDbDto;
                    }
                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, data.getWasteCode()));

                    Long menuId = feignService.getIdByMenuName("其他入库");
                    AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
                    SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
                    MiscellaneousReceiptDetail miscellaneousReceiptDetail = new MiscellaneousReceiptDetail();

                    //如果配置了送检,则校验是否配了检验方案
                    if (sysDocument.getDocInspectionMark()==1){

                        List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                        if (documentCheckDtoList==null){
                            throw new GlobalException("请先在单据配置中配置送检方案");
                        }

                        QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
                        qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
                        qualitySchemeConfigurationVo.setItemRank(documentCheckDtoList.get(0).getCheckSubmit());
                        qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
                        qualitySchemeConfigurationVo.setMaterialCode(data.getWasteCode());
                        boolean check = qualityFeginService.check(qualitySchemeConfigurationVo);

                        if (!check){
                            throw new GlobalException("该物料不存在对应的检验方案");

                        }
                    }

                    //如果对应的编码相等，就将该明细存入
                    if (byId.getMaterialCode().equals(data.getWasteCode())) {
                        //是否配置了送检
                        if (sysDocument.getDocInspectionMark() == 1) {
                            //修改明细状态为待送检
                            miscellaneousReceiptDetail.setStatus(1);
                        } else {
                            //修改明细状态为待交接
                            miscellaneousReceiptDetail.setStatus(2);
                        }

                        //查询该物料是否入库过
                        WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()).eq(WmsStockInfo::getWsiMaterialStatus, 2));

                        if (wmsStockInfo != null) {
                            pickingRestDbDto.setMessage("该数据已经入库");
                            pickingRestDbDto.setCode("500");
                            return pickingRestDbDto;
                        }

                        miscellaneousReceiptDetail.setMaterialNumber(materialNumber);
                        miscellaneousReceiptDetail.setGrossWeight(data.getGrossWeight());
                        miscellaneousReceiptDetail.setNetWeight(data.getNetWeight());
                        miscellaneousReceiptDetail.setMaterialCode(data.getWasteCode());
                        miscellaneousReceiptDetail.setReceiptQuantity(1);
                        miscellaneousReceiptDetail.setMiscellaneousId(byId.getId());
                        miscellaneousReceiptDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                        miscellaneousReceiptDetail.setWarehouseInBy(SecurityUtils.getUsername());
                        miscellaneousReceiptDetailService.save(miscellaneousReceiptDetail);


                        //向仓库表中添加对应的数据
                        WmsStockInfo wmsStockInfo1 = new WmsStockInfo();
                        wmsStockInfo1.setWsiMaterialNumber(pickingRestDbVo.getInputValue())
                                .setWsiMaterialCode(data.getWasteCode())
                                .setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()))
                                .setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()))
                                .setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()))
                                .setWsiMaterialNum(1)
                                .setWsiDocNum(miscellaneousReceipt.getReceiptNo())
                                .setWsiConnectNum(miscellaneousReceipt.getRelationOrderNo())
                                .setWsiMaterialStatus(2)
                                .setWsiMaterialGrade("4")
                                .setWsiGorssWeight(data.getGrossWeight())
                                .setWsiNetWeight(data.getNetWeight())
                                .setWsiReveiveTime(new Date())
                                .setCreateUser(SecurityUtils.getUsername())
                                .setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()))
                                .setWsiMaterialType(publicGoods.getMaterialType())
                                .setCreateTime(new Date());
                        wmsStockInfoService.save(wmsStockInfo1);

                        //回传废料管理入库时间
                        String wasteScrapNumber = data.getWasteScrapNumber();
                        feignProductionService.upDateInTime(wasteScrapNumber);

                    } else {
                        pickingRestDbDto.setMessage("没有匹配的物料，请核实!");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }

                    //获取单位字典值
                    List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                    Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

                    //判断单位
                    if ("2".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是千克
                        if (miscellaneousReceipt.getActualQuantity() == null || "".equals(miscellaneousReceipt.getActualQuantity())) {
                            miscellaneousReceipt.setActualQuantity(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                            //修改采购入库信息入库重量
                            miscellaneousReceipt.setWarehousingWeight(data.getNetWeight());
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(miscellaneousReceipt.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                            String s = bigDecimal.add(bigDecimal1).toString();
                            miscellaneousReceipt.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(miscellaneousReceipt.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            miscellaneousReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    } else if ("3".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                        if (miscellaneousReceipt.getActualQuantity() == null || "".equals(miscellaneousReceipt.getActualQuantity())) {
                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                            BigDecimal divide = bigDecimal.divide(new BigDecimal("1000"));
                            miscellaneousReceipt.setActualQuantity(divide.toString());
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(miscellaneousReceipt.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            miscellaneousReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(miscellaneousReceipt.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                            BigDecimal divide = bigDecimal1.divide(new BigDecimal("1000"));
                            String s = bigDecimal.add(divide).toString();
                            miscellaneousReceipt.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(miscellaneousReceipt.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            miscellaneousReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    } else {
                        if (miscellaneousReceipt.getActualQuantity() == null || "".equals(miscellaneousReceipt.getActualQuantity())) {
                            miscellaneousReceipt.setActualQuantity(String.valueOf(miscellaneousReceiptDetail.getReceiptQuantity()));
                            //修改采购入库信息入库重量
                            miscellaneousReceipt.setWarehousingWeight(miscellaneousReceiptDetail.getNetWeight());
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(miscellaneousReceipt.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getReceiptQuantity()));
                            String s = bigDecimal.add(bigDecimal1).toString();
                            miscellaneousReceipt.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(miscellaneousReceipt.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            miscellaneousReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    }
                    int warehousingNum = miscellaneousReceipt.getWarehousingNum();
                    if (warehousingNum == 0) {
                        miscellaneousReceipt.setWarehousingNum(1);
                    } else {
                        miscellaneousReceipt.setWarehousingNum(warehousingNum + 1);
                    }

                    pickingRestDbDto.setQuantityIdentification(miscellaneousReceipt.getPlannedWeight() + "/" + miscellaneousReceipt.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setMessage("物料号码:" + miscellaneousReceiptDetail.getMaterialNumber() + "," + "净重:" + miscellaneousReceiptDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + miscellaneousReceiptDetail.getReceiptQuantity() + "," + "录入成功");
                    pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                    pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(miscellaneousReceipt.getWarehousingNum()));


                    double aDouble = Double.parseDouble(miscellaneousReceipt.getActualQuantity());
                    double plannedWeight = miscellaneousReceipt.getPlannedWeight();

                    //判断是否配置了超收
                    if (sysDocument.getDocExcessMark() == 2 && publicGoods.getMaterialClosed() == 2) {
                        if (Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(plannedWeight)) {
                            //如果配置了送检
                            if (sysDocument.getDocInspectionMark() == 1) {
                                miscellaneousReceipt.setStatus(3);
                                updateById(miscellaneousReceipt);

                                // 生成品质检验单
                                if (sysDocument.getDocCode() == null) {
                                    throw new GlobalException("未进行单据配置");
                                }
                                List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                                if (documentCheckDtoList.size() < 1) {
                                    throw new GlobalException("未进行检验单生成配置");
                                }
                                //获取明细列表
                                List<MiscellaneousReceiptDetail> salesReturnDetailList = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, miscellaneousReceipt.getId()));
                                StringBuilder stringBuilder = new StringBuilder();
                                for (MiscellaneousReceiptDetail entity : salesReturnDetailList) {
                                    stringBuilder.append(entity.getBatchNo()).append(",");
                                }
                                StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);

                                for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                                    if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                                        QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                                        qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                                        qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                                        qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                                        qualityInspectionDocumentVo.setMaterialCode(miscellaneousReceipt.getMaterialCode());
                                        qualityInspectionDocumentVo.setBatchNo(stringBuilder1.toString());
                                        qualityInspectionDocumentVo.setAssociatedNo(miscellaneousReceipt.getReceiptNo());
                                        qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                                        qualityInspectionDocumentVo.setModeType(14);

                                        List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                                        for (MiscellaneousReceiptDetail entity : salesReturnDetailList) {
                                            MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                            materialNumberAndBatchNoVo.setBatchNo(entity.getBatchNo());
                                            materialNumberAndBatchNoVo.setMaterialNumber(entity.getMaterialNumber());
                                            materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                                        }
                                        qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

//                                        AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
//                                        String code = add.get("code").toString();
                                        boolean b = qualityFeginService.addWares(qualityInspectionDocumentVo);
                                        if (!b) {
                                            pickingRestDbDto.setMessage("生成品质检验单失败");
                                            pickingRestDbDto.setCode("500");
                                            return pickingRestDbDto;
                                        }
                                    }
                                }
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            }
                            //如果配置了交接
                            if (sysDocument.getDocHandoverMark() == 1) {
                                miscellaneousReceipt.setStatus(4);
                                updateById(miscellaneousReceipt);
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            } else {
                                miscellaneousReceipt.setStatus(5);
                                updateById(miscellaneousReceipt);
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            }
                        }
                    }
                    miscellaneousReceipt.setStatus(2);
                    updateById(miscellaneousReceipt);
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
            }
            //条码撤销
            if ("2".equals(pickingRestDbVo.getType())) {
//                //如果是第一步，需要查询库位信息
//                if (pickingRestDbVo.getExecutionOrder() == 1) {
//                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
//                    if (warehouseCode.getCombinationName() == null) {
//                        pickingRestDbDto.setMessage("没有该仓库信息，请核实!");
//                        pickingRestDbDto.setCode("500");
//                        return pickingRestDbDto;
//                    }
//                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
//                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
//                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
//                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
//                    pickingRestDbDto.setMessage("操作成功");
//                    pickingRestDbDto.setCode("200");
//                    return pickingRestDbDto;
//                }
                //如果是第二步，需要根据物料号码查询明细信息
//                if (pickingRestDbVo.getExecutionOrder() == 2) {
                //查询该条码是否扫描过
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()).eq(WmsStockInfo::getWsiMaterialStatus, 2));
                if (wmsStockInfo == null) {
                    pickingRestDbDto.setMessage("撤销失败，请核实后再录入");
                    pickingRestDbDto.setCode("500");
                    return pickingRestDbDto;
                }
                wmsStockInfoMapper.deleteById(wmsStockInfo);

                //同时删除采购入库明细状态
                MiscellaneousReceiptDetail miscellaneousReceiptDetail = miscellaneousReceiptDetailMapper.selectOne(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));

                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, miscellaneousReceipt.getMaterialCode()));
                //获取单位字典值
                List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
                //设置返回信息
                pickingRestDbDto.setMessage("物料号码:" + miscellaneousReceiptDetail.getMaterialNumber() + "," + "净重:" + miscellaneousReceiptDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + miscellaneousReceiptDetail.getReceiptQuantity() + "," + "撤销成功");
                pickingRestDbDto.setQuantityIdentification(miscellaneousReceipt.getPlannedWeight() + "/" + miscellaneousReceipt.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                pickingRestDbDto.setWarehouseNumber(String.valueOf(miscellaneousReceipt.getWarehousingNum()));


                List<MiscellaneousReceiptDetail> list = miscellaneousReceiptDetailService.list();
                //判断条数修改采购入库状态
                if (list.size() == 0) {
                    miscellaneousReceipt.setStatus(1);
                    miscellaneousReceipt.setWarehousingNum(0);
                    miscellaneousReceipt.setWarehousingWeight(0);
                    miscellaneousReceipt.setActualQuantity("0");
                } else {
                    //判断单位
                    BigDecimal bigDecimal = new BigDecimal(miscellaneousReceipt.getActualQuantity());
                    BigDecimal bigDecimal1;
                    if ("2".equals(publicGoods.getMaterialUnit())) {
                        //如果是千克
                        bigDecimal1 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                        String s = bigDecimal.subtract(bigDecimal1).toString();
                        miscellaneousReceipt.setActualQuantity(s);
                        //修改采购入库信息入库重量
                        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(miscellaneousReceipt.getWarehousingWeight()));
                        BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                        String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                        miscellaneousReceipt.setWarehousingWeight(Double.parseDouble(s1));
                    } else if ("3".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000

                        BigDecimal bigDecimalNetWeight = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                        BigDecimal divide = bigDecimalNetWeight.divide(new BigDecimal("1000"));
                        String s = bigDecimal.subtract(divide).toString();
                        miscellaneousReceipt.setActualQuantity(s);
                        //修改采购入库信息入库重量
                        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(miscellaneousReceipt.getWarehousingWeight()));
                        BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                        String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                        miscellaneousReceipt.setWarehousingWeight(Double.parseDouble(s1));
                    } else {
                        //不是千克
                        bigDecimal1 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getReceiptQuantity()));
                        String s = bigDecimal.subtract(bigDecimal1).toString();
                        miscellaneousReceipt.setActualQuantity(s);
                        //修改采购入库信息入库重量
                        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(miscellaneousReceipt.getWarehousingWeight()));
                        BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight()));
                        String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                        miscellaneousReceipt.setWarehousingWeight(Double.parseDouble(s1));
                    }
                    //入库数量
                    miscellaneousReceipt.setWarehousingNum(miscellaneousReceipt.getWarehousingNum() - 1);
                }
                updateById(miscellaneousReceipt);

                miscellaneousReceiptDetailMapper.deleteById(miscellaneousReceiptDetail);
                pickingRestDbDto.setCode("200");
                return pickingRestDbDto;
//                }
            }
        } else {
            pickingRestDbDto.setMessage("只能操作待入库和入库中得数据");
            pickingRestDbDto.setCode("500");
            return pickingRestDbDto;
        }
        pickingRestDbDto.setMessage("步骤不正确,请核实!");
        pickingRestDbDto.setCode("500");
        return pickingRestDbDto;
    }

    /**
     * 其它入库拣货撤销
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCancellation(PickingRestDbVo pickingRestDbVo) {

        //根据其它入库id获取明细数据
        List<MiscellaneousReceiptDetail> miscellaneousReceiptDetailList = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, pickingRestDbVo.getId()));
        if (miscellaneousReceiptDetailList.size() < 1) {
            throw new GlobalException("不存在明细，请核实!");
        }
        List<String> materialNumberList = new ArrayList<>();
        for (MiscellaneousReceiptDetail entity : miscellaneousReceiptDetailList) {
            materialNumberList.add(entity.getMaterialNumber());
        }
        //根据物料号码查询仓库信息
        List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
        if (wmsStockInfoList.size() > 0) {
            //删除仓储数据
            wmsStockInfoMapper.deleteBatchIds(wmsStockInfoList);
        }
        //删除明细数据
        miscellaneousReceiptDetailMapper.deleteBatchIds(miscellaneousReceiptDetailList);
        //修改销售退货状态
        MiscellaneousReceipt miscellaneousReceipt = getById(pickingRestDbVo.getId());
        miscellaneousReceipt.setStatus(1);
        miscellaneousReceipt.setWarehousingNum(0);
        miscellaneousReceipt.setWarehousingWeight(0);
        miscellaneousReceipt.setActualQuantity("0");
        //删除关联的检验单
        String relevanceDoc = miscellaneousReceipt.getReceiptNo();
        qualityFeginService.removeDoc(relevanceDoc);
        return updateById(miscellaneousReceipt);
    }

    /**
     * 其它入库拣货完成
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCompleted(PickingRestDbVo pickingRestDbVo) throws Exception {
        MiscellaneousReceipt miscellaneousReceipt = getById(pickingRestDbVo.getId());
//        //需求量
//        double aDouble = Double.parseDouble(miscellaneousReceipt.getActualQuantity());
//        //计划量
//        double plannedWeight = miscellaneousReceipt.getPlannedWeight();

        PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, miscellaneousReceipt.getMaterialCode()));

        Long menuId = feignService.getIdByMenuName("其他入库");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //配置了超收
//        if (sysDocument.getDocExcessMark() == 1) {
//            if (Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(plannedWeight)) {
        //如果配置了送检
        if (sysDocument.getDocInspectionMark() == 1) {
            miscellaneousReceipt.setStatus(3);
            // 生成品质检验单
            if (sysDocument.getDocCode() == null) {
                throw new GlobalException("未进行单据配置");
            }
            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
            if (documentCheckDtoList.size() < 1) {
                throw new GlobalException("未进行检验单生成配置");
            }
            //通过物料编码获取物料类别
            //PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSaleDetail.getItemCode()));
            //获取明细列表
            List<MiscellaneousReceiptDetail> salesReturnDetailList = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, miscellaneousReceipt.getId()));
            StringBuilder stringBuilder = new StringBuilder();
            for (MiscellaneousReceiptDetail entity : salesReturnDetailList) {
                stringBuilder.append(entity.getBatchNo()).append(",");
            }
            StringBuilder stringBuilderBatch = stringBuilder.deleteCharAt(stringBuilder.length() - 1);

            for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                    QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                    qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                    qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                    qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                    qualityInspectionDocumentVo.setMaterialCode(miscellaneousReceipt.getMaterialCode());
                    qualityInspectionDocumentVo.setBatchNo(stringBuilderBatch.toString());
                    qualityInspectionDocumentVo.setAssociatedNo(miscellaneousReceipt.getReceiptNo());
                    qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                    qualityInspectionDocumentVo.setModeType(14);

                    List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                    for (MiscellaneousReceiptDetail entity : salesReturnDetailList) {
                        MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                        materialNumberAndBatchNoVo.setBatchNo(entity.getBatchNo());
                        materialNumberAndBatchNoVo.setMaterialNumber(entity.getMaterialNumber());
                        materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                    }
                    qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                    AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
                    String code = add.get("code").toString();
                    if ("500".equals(code)) {
                        throw new GlobalException("生成品质检验单失败");
                    }
                }
            }
            return updateById(miscellaneousReceipt);
        }
        //如果配置了交接
        if (sysDocument.getDocHandoverMark() == 1) {
            miscellaneousReceipt.setStatus(4);
            return updateById(miscellaneousReceipt);
        }
//            }
//        }
        miscellaneousReceipt.setStatus(5);
        return updateById(miscellaneousReceipt);
    }

    /**
     * 其它入库交接
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestHandoverDto handover(PickingRestDbVo pickingRestDbVo) {
        PickingRestHandoverDto pickingRestHandoverDto = new PickingRestHandoverDto();
        MiscellaneousReceipt miscellaneousReceipt = getById(pickingRestDbVo.getId());
        //获取单位字典值
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        if (miscellaneousReceipt.getStatus() != 4) {
            pickingRestHandoverDto.setResultCode("500");
            pickingRestHandoverDto.setMessage("只能操作待交接的单据");
            return pickingRestHandoverDto;
        }
        //获取单据配置信息
        Long menuId = feignService.getIdByMenuName("其他入库");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //第一步根据工号查询交接人
        //如果是整单
        if (sysDocument.getDocHandoverMethod() == 3) {
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                AjaxResult byUserName = remoteUserService.getByUserName(userName);
                SysUser userInfo = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);

                if (userInfo.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(sysDocument.getDocHandoverMethod());
                pickingRestHandoverDto.setResultCode("200");
//            return pickingRestHandoverDto;
//        }

                //第二步
//        if (pickingRestDbVo.getExecutionOrder() == 2) {
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, miscellaneousReceipt.getMaterialCode()));

//            //判断单据状态是否为待交接
//            if (miscellaneousReceipt.getStatus() == 4) {

                BigDecimal bigDecimalNetWeight = new BigDecimal(0);
                //根据id获取明细信息
                List<MiscellaneousReceiptDetail> miscellaneousReceiptDetailList = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, pickingRestDbVo.getId()));
                for (MiscellaneousReceiptDetail entity : miscellaneousReceiptDetailList) {
                    entity.setStatus(3);
                    bigDecimalNetWeight = bigDecimalNetWeight.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                }
                miscellaneousReceiptDetailService.updateBatchById(miscellaneousReceiptDetailList);
                //修改其它出库状态为已经完成
                miscellaneousReceipt.setStatus(5);
                miscellaneousReceipt.setHandoverWeight(Double.parseDouble(bigDecimalNetWeight.toString()));
                miscellaneousReceipt.setHandoverNum(miscellaneousReceiptDetailList.size());
                updateById(miscellaneousReceipt);

                //设置出参数据
                pickingRestHandoverDto.setQuantityIdentification(miscellaneousReceipt.getWarehousingWeight() + "/" + bigDecimalNetWeight + unitMap.get(publicGoods.getMaterialUnit()));
                pickingRestHandoverDto.setOutHandoverActual(miscellaneousReceiptDetailList.size() + "/" + miscellaneousReceiptDetailList.size());
                pickingRestHandoverDto.setMessage("单据号:" + miscellaneousReceipt.getReceiptNo() + "," + "总净重:" + bigDecimalNetWeight + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + miscellaneousReceiptDetailList.size() + "," + "交接成功");
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
//            }
        }

        //如果是批次
        if (sysDocument.getDocHandoverMethod() == 2) {
            //第一步根据工号查询交接人
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                AjaxResult byUserName = remoteUserService.getByUserName(userName);
                SysUser userInfo = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);

                if (userInfo.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(sysDocument.getDocHandoverMethod());
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }

            if (pickingRestDbVo.getExecutionOrder() == 2) {
                //通过批次号查询明细数据
                List<MiscellaneousReceiptDetail> miscellaneousReceiptDetailList = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getBatchNo, pickingRestDbVo.getInputValue()));
                if (miscellaneousReceiptDetailList.size() > 0) {
                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, miscellaneousReceiptDetailList.get(0).getMaterialCode()));

                    BigDecimal bigDecimalHand = new BigDecimal(0);
                    for (MiscellaneousReceiptDetail entity : miscellaneousReceiptDetailList) {
                        entity.setStatus(3);
                        bigDecimalHand = bigDecimalHand.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                    }
                    miscellaneousReceiptDetailService.updateBatchById(miscellaneousReceiptDetailList);
                    //修改仓库表数据
                    List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, pickingRestDbVo.getInputValue()));
                    for (WmsStockInfo info : wmsStockInfoList) {
                        info.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfoList);
                    //交接重量
                    BigDecimal handoverWeight = bigDecimalHand.add(new BigDecimal(String.valueOf(miscellaneousReceipt.getHandoverWeight())));

                    //交接数量
                    BigDecimal handoverNum = new BigDecimal(miscellaneousReceiptDetailList.size()).add(new BigDecimal(miscellaneousReceipt.getHandoverNum()));
                    //入库数量
                    List<MiscellaneousReceiptDetail> detailListById = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, pickingRestDbVo.getId()));
                    boolean isTrue = true;
                    for (MiscellaneousReceiptDetail entity : miscellaneousReceiptDetailList) {
                        if (entity.getStatus() != 3) {
                            isTrue = false;
                            break;
                        }
                    }
                    //如果明细都是已完成，就修改其他入库为已完成
                    if (isTrue) {
                        miscellaneousReceipt.setStatus(5);
                    }
                    miscellaneousReceipt.setHandoverWeight(Double.parseDouble(handoverWeight.toString()));
                    miscellaneousReceipt.setHandoverNum(Integer.parseInt(handoverNum.toString()));
                    updateById(miscellaneousReceipt);

                    //设置出参内容
                    pickingRestHandoverDto.setQuantityIdentification(miscellaneousReceipt.getWarehousingWeight() + "/" + handoverWeight + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestHandoverDto.setOutHandoverActual(detailListById.size() + "/" + handoverNum);
                    pickingRestHandoverDto.setMessage("批次号:" + pickingRestDbVo.getInputValue() + "," + "总净重:" + handoverWeight + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + miscellaneousReceiptDetailList.size() + "," + "交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                    return pickingRestHandoverDto;

                } else {
                    pickingRestHandoverDto.setMessage("没有该批次号的数据，请核实后再操作");
                    pickingRestHandoverDto.setResultCode("500");
                    return pickingRestHandoverDto;
                }
            }
        }

        //单个物料
        if (sysDocument.getDocHandoverMethod() == 1) {
            //第一步根据工号查询交接人
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                AjaxResult byUserName = remoteUserService.getByUserName(userName);
                SysUser userInfo = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);

                if (userInfo.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(sysDocument.getDocHandoverMethod());
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
            if (pickingRestDbVo.getExecutionOrder() == 2) {
                //交接数量
                BigDecimal handoverNum = new BigDecimal(1).add(new BigDecimal(pickingRestDbVo.getHandoverNum()));

                //根据物料条码获取明细信息
                MiscellaneousReceiptDetail miscellaneousReceiptDetail = miscellaneousReceiptDetailMapper.selectOne(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, miscellaneousReceiptDetail.getMaterialCode()));

                //修改该明细状态为已经完成
                miscellaneousReceiptDetail.setStatus(3);
                miscellaneousReceiptDetailService.updateById(miscellaneousReceiptDetail);
                //修改仓库表数据
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, miscellaneousReceiptDetail.getMaterialNumber()));
                wmsStockInfo.setWsiMaterialStatus(2);
                wmsStockInfoService.updateById(wmsStockInfo);
                //交接重量
                BigDecimal handoverWeight = new BigDecimal(String.valueOf(miscellaneousReceiptDetail.getNetWeight())).add(new BigDecimal(String.valueOf(miscellaneousReceipt.getHandoverWeight())));
                //判断明细是否都已经交接成功
                List<MiscellaneousReceiptDetail> miscellaneousReceiptDetailList = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, pickingRestDbVo.getId()));
                boolean isTrue = true;
                for (MiscellaneousReceiptDetail entity : miscellaneousReceiptDetailList) {
                    if (entity.getStatus() != 3) {
                        isTrue = false;
                        break;
                    }
                }
                //如果明细都是已完成，就修改其他入库为已完成
                if (isTrue) {
                    updateById(miscellaneousReceipt);
                }
                miscellaneousReceipt.setHandoverWeight(Double.parseDouble(handoverWeight.toString()));
                miscellaneousReceipt.setHandoverNum(Integer.parseInt(handoverNum.toString()));
                updateById(miscellaneousReceipt);

                //设置出参内容
                pickingRestHandoverDto.setQuantityIdentification(miscellaneousReceipt.getWarehousingWeight() + "/" + handoverWeight + unitMap.get(publicGoods.getMaterialUnit()));
                pickingRestHandoverDto.setOutHandoverActual(miscellaneousReceiptDetailList.size() + "/" + handoverNum);
                pickingRestHandoverDto.setMessage("物料号码:" + miscellaneousReceiptDetail.getMaterialNumber() + "," + "总净重:" + miscellaneousReceiptDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + 1 + "," + "交接成功");
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
        }
//    } else{
//        pickingRestHandoverDto.setMessage("只能操作待交接的单据");
//        pickingRestHandoverDto.setResultCode("500");
//        return pickingRestHandoverDto;
//    }
//        }
        return pickingRestHandoverDto;
    }

    /**
     * 其他入库品质回传状态(fegin调用)
     *
     * @param updateStatusByQualityVo
     * @return
     */
    @Override
    public boolean updateStatusByQuality(UpdateStatusByQualityVo updateStatusByQualityVo) {
        Long menuId = feignService.getIdByMenuName("其他入库");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //获取完工入库及对应明细信息
        MiscellaneousReceipt miscellaneousReceipt = miscellaneousReceiptMapper.selectOne(new QueryWrapper<MiscellaneousReceipt>().lambda().eq(MiscellaneousReceipt::getReceiptNo, updateStatusByQualityVo.getAssociatedNo()));

        List<MiscellaneousReceiptDetail> miscellaneousReceiptDetails = miscellaneousReceiptDetailMapper.selectList(new QueryWrapper<MiscellaneousReceiptDetail>().lambda().eq(MiscellaneousReceiptDetail::getMiscellaneousId, miscellaneousReceipt.getId()));
        //如果单据状态为待检验
        if (miscellaneousReceipt.getStatus() == 3) {
            //如果配置了交接
            if (sysDocument.getDocHandoverMark() == 1) {
                miscellaneousReceipt.setStatus(4);
                for (MiscellaneousReceiptDetail entity : miscellaneousReceiptDetails) {
                    entity.setStatus(2);
                }
            } else {
                for (MiscellaneousReceiptDetail entity : miscellaneousReceiptDetails) {
                    entity.setStatus(3);
                }
                miscellaneousReceipt.setStatus(5);
            }
        }
        if (miscellaneousReceiptDetails.size() > 0) {
            miscellaneousReceiptDetailService.updateBatchById(miscellaneousReceiptDetails);
        }

        return updateById(miscellaneousReceipt);
    }
}
